/**
 * Your application code goes here
 */
package userclasses;

import com.sun.lwuit.CheckBox;
import com.sun.lwuit.Component;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Display;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.List;
import com.sun.lwuit.TextArea;
import generated.StateMachineBase;
import com.sun.lwuit.events.*;
import com.sun.lwuit.geom.Dimension;
import com.sun.lwuit.io.ConnectionRequest;
import com.sun.lwuit.io.NetworkManager;
import com.sun.lwuit.io.Storage;
import com.sun.lwuit.io.services.facebook.FaceBookAccess;
import com.sun.lwuit.io.services.facebook.User;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.list.DefaultListModel;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;

/**
 *
 * @author Your name here
 */
public class StateMachine extends StateMachineBase {

    private User me;

    public StateMachine(String resFile) {
        super(resFile);
        // do not modify, write code in initVars and initialize class members there,
        // the constructor might be invoked too late due to race conditions that might occur
    }

    /**
     * this method should be used to initialize variables instead of
     * the constructor/class scope to avoid race conditions
     */
    protected void initVars() {
        try {
            FaceBookAccess.getInstance().authenticate("125527160846284", "http://a.b.c/", new String[]{"user_photos", "friends_photos", "publish_stream", "read_stream", "user_relationships", "user_birthday", "friends_birthday", "friends_relationships", "read_mailbox", "user_events", "friends_events", "user_about_me"});

            me = new User();
            FaceBookAccess.getInstance().getUser("me", me, new ActionListener() {

                public void actionPerformed(ActionEvent evt) {
                    System.out.println("returned user");
                }
            });
        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }

    protected void onShare_ButtonAction(Component c, ActionEvent event) {
        try {
            // If the resource file changes the names of components this call will break notifying you that you should fix the code
            super.onShare_ButtonAction(c, event);

            final Dialog dialog = (Dialog) createContainer(getResourceFilePath(), "WaitDialog");
            dialog.showPacked(BorderLayout.CENTER, false);
            FaceBookAccess.getInstance().postLike("132932836804285_133031760127726");
            dialog.dispose();

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    protected void onShare_Button1Action(Component c, ActionEvent event) {
        // If the resource file changes the names of components this call will break notifying you that you should fix the code
        super.onShare_Button1Action(c, event);
        final Dialog dialog = (Dialog) createContainer(getResourceFilePath(), "WaitDialog");
        TextArea txt = findMessage(c.getComponentForm());
        dialog.showPacked(BorderLayout.CENTER, false);
        try {
            FaceBookAccess.getInstance().postComment("132932836804285_133031760127726", txt.getText());
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        dialog.dispose();

    }

    protected void beforeProfile(Form f) {
        // If the resource file changes the names of components this call will break notifying you that you should fix the code
        super.beforeProfile(f);
        Label pic = findProfilePic(f);
        try {
            FaceBookAccess.getInstance().getPicture(me.getId(), pic, null, false);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        Label name = findProfileName(f);
        name.setText(me.getName());
        Label last = findLastname(f);
        last.setText(me.getLast_name());
        Label birth = findBirthday(f);
        birth.setText(me.getBirthday());
    
    }

    protected void postFriends(final Form f) {
        // If the resource file changes the names of components this call will break notifying you that you should fix the code
        super.postFriends(f);
        try {
            // If the resource file changes the names of components this call will break notifying you that you should fix the code
            final List friends = findList(f);
            
            Image photoPlaceHolder = Image.createImage(50, 50);
            final Hashtable prototype = new Hashtable();
            prototype.put("pic", photoPlaceHolder);
            friends.setRenderingPrototype(prototype);

            ((DefaultListModel) friends.getModel()).removeAll();
            FaceBookAccess.getInstance().getUserFriends(me.getId(), (DefaultListModel) friends.getModel(), new ActionListener() {

                public void actionPerformed(ActionEvent evt) {
                    
                    new Thread(new Runnable() {

                        public void run() {
                            for (int i = 0; i < friends.getModel().getSize(); i++) {
                                Hashtable table = ((Hashtable) friends.getModel().getItemAt(i));
                                String id = (String) table.get("id");
                                try {
                                    FaceBookAccess.getInstance().getPicture(id, friends, i, "pic", new Dimension(50, 50), false);
                                } catch (IOException ex) {
                                    ex.printStackTrace();
                                }
                            }
                        }
                    }).start();
                    
                }
            });

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    
    }

    protected boolean onMainExit() {
        // If the resource file changes the names of components this call will break notifying you that you should fix the code
        boolean val = super.onMainExit();
        CheckBox cb =  findCache(Display.getInstance().getCurrent());
        //this will clear all storage data including the user login credentials.
        if(cb.isSelected()){
            Storage.getInstance().clearStorage();
        }
        Display.getInstance().exitApplication();
        return val;
    }

    protected void exitFriends(Form f) {
        // If the resource file changes the names of components this call will break notifying you that you should fix the code
        super.exitFriends(f);
        emptyNetworkTasks();
    }
    
    private void emptyNetworkTasks() {
        Enumeration tasks = NetworkManager.getInstance().enumurateQueue();
        while (tasks.hasMoreElements()) {
            ConnectionRequest req = (ConnectionRequest) tasks.nextElement();
            req.kill();
        }
        FaceBookAccess.getInstance().killCurrentRequest();
    }
    


    protected void postAlbums(Form f) {
        // If the resource file changes the names of components this call will break notifying you that you should fix the code
        super.postAlbums(f);
        try {
            // If the resource file changes the names of components this call will break notifying you that you should fix the code
            final List albums = findAlbums(f);
            
            Image photoPlaceHolder = Image.createImage(50, 50);
            final Hashtable prototype = new Hashtable();
            prototype.put("pic", photoPlaceHolder);
            albums.setRenderingPrototype(prototype);

            ((DefaultListModel) albums.getModel()).removeAll();
            
            FaceBookAccess.getInstance().getUserAlbums(me.getId(), (DefaultListModel) albums.getModel(), new ActionListener() {

                public void actionPerformed(ActionEvent evt) {
                    
                    new Thread(new Runnable() {

                        public void run() {
                            for (int i = 0; i < albums.getModel().getSize(); i++) {
                                Hashtable table = ((Hashtable) albums.getModel().getItemAt(i));
                                System.out.println("table " + table);
                                String id = (String) table.get("id");
                                if(id != null){
                                    try {
                                        FaceBookAccess.getInstance().getPicture(id, albums, i, "pic", new Dimension(50, 50), true);
                                    } catch (IOException ex) {
                                        ex.printStackTrace();
                                    }
                                }
                            }
                        }
                    }).start();

                    
                }
            });

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    
    }
}
